package utils

import (
	"errors"
)

// U32ToBytes uint32转化为字节数组，大端
func U32ToBytes(u uint32) []byte {
	result := make([]byte, 4)
	result[3] = byte(u & 0xff)
	result[2] = byte(u & 0xff00 >> 8)
	result[1] = byte(u & 0xff0000 >> 16)
	result[0] = byte(u & 0xff000000 >> 24)
	return result
}

// BytesToU32 字节数组转化为uint32，大端
func BytesToU32(b []byte) (uint32, error) {
	if len(b) < 4 {
		return 0, errors.New("slice len less then 4, can't convert to uint32")
	}
	var result uint32 = 0
	result |= uint32(b[3])
	result |= uint32(b[2]) << 8
	result |= uint32(b[1]) << 16
	result |= uint32(b[0]) << 24
	return result, nil
}

// U16ToBytes uint16转化为字节数组，大端
func U16ToBytes(u uint16) []byte {
	result := make([]byte, 2)
	result[1] = byte(u & 0xff)
	result[0] = byte(u & 0xff00 >> 8)
	return result
}

// BytesToU16 字节数组转化为uint16，大端
func BytesToU16(b []byte) (uint16, error) {
	if len(b) < 2 {
		return 0, errors.New("slice len less then 2, can't convert to uint16")
	}
	var result uint16 = 0
	result |= uint16(b[1])
	result |= uint16(b[0]) << 8
	return result, nil
}

func I32ToBytes(i int32) []byte {
	if i >= 0 {
		return U32ToBytes(uint32(i))
	} else {
		b := U32ToBytes(uint32(-i))
		b[0] |= 0x01 << 7
		return b
	}
}

func BytesToI32(b []byte) (int32, error) {
	if len(b) < 4 {
		return 0, errors.New("slice len less then 4, can't convert to uint32")
	}
	negNum := false
	op := (b[0] & (0x01 << 7)) >> 7
	if op != 0 {
		negNum = true
	}
	bb := b[0]
	var mask = ^(byte(0x01) << 7)
	bb &= mask
	var result uint32 = 0
	result |= uint32(b[3])
	result |= uint32(b[2]) << 8
	result |= uint32(b[1]) << 16
	result |= uint32(bb) << 24
	if negNum {
		return -int32(result), nil
	}
	return int32(result), nil
}
